/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			ETVpCmd_EditSubI.cc
  \date			Sep 2011
  \author		TNick

  \brief		Contains the implementation for ETVpCmd_EditSubI class


  Copyright (c) 2011, Nicu Tofan
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
 * Neither the name of the copyright holder nor the
   names of its contributors may be used to endorse or promote products
   derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL NICU TOFAN BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include	<QMouseEvent>

#include	<sheet/ETSheetView.h>
#include	<sheet/ETSheet.h>
#include	<sheet/ETI_CplxTxt.h>
#include	<sheet/subitems/ETSI_SText.h>

#include	"ETVpCmd_EditSubI.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */

/* ------------------------------------------------------------------------- */
ETVpCmd_EditSubI::ETVpCmd_EditSubI	( void )
	: ETVpCommand ()
{
	p_editor = NULL;
	it_in_ed = NULL;
	sit_in_ed = NULL;
	viwp = NULL;

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
ETVpCmd_EditSubI::~ETVpCmd_EditSubI	( void )
{

	if (p_editor != NULL)
	{
		LnEditSI * ed = p_editor;
		p_editor = NULL;
		ed->deleteLater();
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool		ETVpCmd_EditSubI::start		(
		ETSheetView * trg_vp)
{

	viwp = trg_vp;
	transf = viwp->transform();

	/* make shure we have a proper sub-item to edit */
	if (sit_in_ed == NULL)
	{

		sit_in_ed = static_cast<ETSI_SText *>(trg_vp->currentSubI());
		it_in_ed = trg_vp->currentItem();

		if (sit_in_ed == NULL)
			return false;
	}

	/* check for proper item type */
	if (sit_in_ed->type() != ETSubItem::TYSTEXT)
	{
		qDebug() << "Can not edit an non-text item. Expected type: "
				 << ETSubItem::TYSTEXT << " recieved type: " << sit_in_ed->type();

	}

	/* cancel the rotation */
	viwp->rotate(-viwp->getRotation());

	/* enshure a proper zoom */
	QRectF box_in_s = sit_in_ed->boxInScene(NULL);
	qreal h_in_px = box_in_s.height() * viwp->getScale();
	qreal scale_now = viwp->getScale();
	if (h_in_px < 40)
	{
		qreal fact = 40 * viwp->getScale() / h_in_px;
		viwp->scale(fact, fact);
		scale_now *= fact;
	}
	else if (h_in_px > 60)
	{
		qreal fact = 1 / (60 * viwp->getScale() / h_in_px);
		viwp->scale(fact, fact);
		scale_now *= fact;
	}

	/* enshure is in visible area */
	qreal wdth_in_px = scale_now * box_in_s.width();
	h_in_px = box_in_s.height() * scale_now;

	QPointF tp_l_px(
				box_in_s.left() * viwp->getScale(),
				box_in_s.top() * viwp->getScale());
	bool b_pop_up = false;
	int dx = 0;
	int dy = 0;
	for (;;)
	{
		/* first, make shure that the the area is large enough to contain
   entire box */
		if (h_in_px > viwp->height() )
		{ /* the height is limitative factor; step to pop-up box directly */
			b_pop_up = true;
			break;
		}
		if (wdth_in_px < 30)
			wdth_in_px = 30;

		if (wdth_in_px > viwp->width())
		{ /* we have a box that is larger than the viewport */

			if (viwp->width() < 100)
			{ /* the viewport is too small; use a text box */
				b_pop_up = true;
				break;
			}
			else
			{ /* the viewport is large enough. Shrink the box */
				wdth_in_px = (viwp->width() * 100) / 128;
			}
		}

		/* we now know that the box fits inside the viewport */
		//viwp->ensureVisible(box_in_s);

		/* check vertical position */
		if (tp_l_px.y() < 0)
		{ /* the box is above the view */
			dy = (int)(tp_l_px.y() - /* this brings the box to top margin */
					   (viwp->height() - h_in_px) / 2); /* and this centers it */
		}
		else if (tp_l_px.y() > (viwp->height() - h_in_px))
		{ /* the box is below the view */
			dy = (int)(tp_l_px.y() - viwp->height() -/* brig it to bottom margin */
					   (viwp->height() - h_in_px) / 2); /* and this centers it */
		}

		/* check horizontal position */
		if (tp_l_px.x() < 0)
		{ /* the box is to the left of the view */
			dx = (int)(tp_l_px.x() - /* this brings the box to left margin */
					   (viwp->width() - wdth_in_px) / 2); /* and this centers it */
		}
		else if (tp_l_px.x() > (viwp->width() - wdth_in_px))
		{ /* the box is to the right of the view */
			dx = (int)(tp_l_px.x() - viwp->width() -/* brig it to right margin */
					   (viwp->width() - wdth_in_px) / 2); /* and this centers it */

		}
		break;
	}

	if (b_pop_up)
	{ /* create a pop-up text box that will handle the input */

	}
	else
	{
		if ((dx != 0) | (dy != 0))
		{ /* translation is needed */
			viwp->translate(
						dx / viwp->getScale(),
						dy / viwp->getScale()
						);
		}

		/* create the editor */
		QRect	ed_r(
					(int)tp_l_px.x()+dx,
					(int)tp_l_px.y()+dy,
					wdth_in_px,
					h_in_px);
		p_editor = new LnEditSI (
					this,
					sit_in_ed->text(),
					ed_r, trg_vp);

		QFont f_lc = sit_in_ed->font();
		f_lc.setPointSize(f_lc.pointSize() * viwp->getScale());
		p_editor->setFont(f_lc);
	}

	return true;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		ETVpCmd_EditSubI::cancel		(
		ETSheetView * trg_vp )
{
	Q_UNUSED(trg_vp);

	/* restore the view matrix */
	viwp->setTransform(transf);

	/* destroy the editor */
	p_editor->close();
	p_editor->deleteLater();

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		ETVpCmd_EditSubI::accepted		(
		ETSheetView * trg_vp )
{
	Q_UNUSED(trg_vp);

	/* save the text */
	sit_in_ed->setText(p_editor->text());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		ETVpCmd_EditSubI::setSubItemToEdit	(
		ETI_CplxTxt * new_it_in_ed, ETSI_SText * new_sit_in_ed)
{
	sit_in_ed = new_sit_in_ed;
	if (new_it_in_ed == NULL)
	{
		if (sit_in_ed == NULL)
		{
			it_in_ed = NULL;
		}
		else
		{
			it_in_ed = sit_in_ed->fatherCplx();
		}
	}
	else
	{
		it_in_ed = new_it_in_ed;
	}
}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
bool		ETVpCmd_EditSubI::mousePress	(
		ETSheetView * vp, QMouseEvent * event)
{
	Q_UNUSED(event);

	ETSheet * scn = static_cast<ETSheet *>(vp->scene());
	Q_UNUSED(scn);

	/* end the command, suggesting succesfull completion */
	vp->acceptCommand();

	/* allow the event to do it's job */
	return true;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
LnEditSI::LnEditSI			(
		ETVpCmd_EditSubI * ed_req, QString s_tx,
		QRect geom, ETSheetView * parent)
	: QLineEdit(parent)
{
	/* cache provided data */
	requester = ed_req;

	/* move in place */
	move(geom.topLeft());
	resize(geom.size());

	/* set the string as requested */
	setText(s_tx);

	/* bright and shiny */
	show();
	setFocus();
}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void		LnEditSI::keyPressEvent		( QKeyEvent * event )
{
	if (event->key() == Qt::Key_Return)
	{
		ETSheetView * vp = static_cast<ETSheetView *>(parent());
		vp->acceptCommand();
	}
	else if (event->key() == Qt::Key_Escape)
	{
		ETSheetView * vp = static_cast<ETSheetView *>(parent());
		vp->cancelCommand();
	}
	else
	{
		QLineEdit::keyPressEvent(event);
	}
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void		LnEditSI::focusOutEvent		( QFocusEvent * e )
{
	/// @todo implement the options for focus lost

	//	if (option_to_accept_when_focus_is_lost == true)
	//	{
	//	ETSheetView * vp = static_cast<ETSheetView *>(parent());
	//	vp->acceptCommand();
	//	}
	//	else if (option_to_cancel_when_focus_is_lost == true)
	//	{
	//	ETSheetView * vp = static_cast<ETSheetView *>(parent());
	//	vp->cancelCommand();
	//	}

	QLineEdit::focusOutEvent(e);
}
/* ========================================================================= */


/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
